package com.adamjwh.pratice.offer;

import java.util.ArrayList;

/**
 * 输入n个整数，找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字，则最小的4个数字是1,2,3,4,。
 */
public class GetLeastNumbers {
    public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
        ArrayList<Integer> list = new ArrayList<>();

        if(input.length <=0 || input.length < k) {
            return list;
        }

        quickSort(input, 0, input.length-1);
        for (int i=0; i<k; i++) {
            list.add(input[i]);
        }

        return list;
    }

    private static void quickSort(int[] arr, int low, int high) {
        if(low >= high) {
            return ;
        }

        int index = partition(arr, low, high);
        quickSort(arr, low, index-1);
        quickSort(arr, index+1, high);
    }

    private static int partition(int[] arr, int low, int high) {
        int key = arr[low];

        while (low < high) {
            while (arr[high] >= key && high >low) {
                high--;
            }
            arr[low] = arr[high];

            while (arr[low] <= key && high > low) {
                low ++;
            }
            arr[high] = arr[low];
        }
        arr[low] = key;

        return low;
    }
}
